/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Web;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using ResourceManager = FourRoads.Links.Controls.ResourceManager;

namespace FourRoads.Links.Controls
{
	/// <summary>
	/// Summary description for ResLinkLinksView.
	/// </summary>
	public class ResLinkLinksView: ResLinkBaseTemplatedWebControl
	{
		#region Child Controls
			LinkSorting _Sorting = null;
			RepeaterPlusNone _Links = null;
		 	StatusMessage _SuggestionReceived = null;
			LinkPageControl _Pager = null;
		#endregion

		public ResLinkLinksView()
		{

		}

		public enum viewType
		{
			Auto,
			DeadLinks,
			Moderation
		}

		public int CurrentPage
		{
			get
			{
				return CSContext.Current.GetIntFromQueryString("Page" , 1);
			}
		}

		[DefaultValue( false )]
		public bool AllowPaging
		{
			get
			{
				if (ViewState["AllowPaging"] == null)
					ViewState["AllowPaging"] = false;

				return (bool)ViewState["AllowPaging"];
			}

			set
			{
				ViewState["AllowPaging"] = value;
			}
		}

		[DefaultValue( 20 )]
		public int PageSize
		{
			get
			{
				if (ViewState["PageSize"] == null)
					ViewState["PageSize"] = 20;

				return (int)ViewState["PageSize"];
			}

			set
			{
				ViewState["PageSize"] = value;
			}
		}

		[DefaultValue( viewType.Auto )]
		public viewType View
		{
			get
			{
				if (ViewState["View"] == null)
					ViewState["View"] = viewType.Auto;

				return (viewType)ViewState["View"];
			}

			set
			{
				ViewState["View"] = value;
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			if (ThisSection.IsActive == false)
			{
				Context.Response.Redirect(Globals.GetSiteUrls().Message((CSExceptionType) RlMessageTypes.ResourceLinkSectionClosed));
			}

			if (!Page.IsPostBack)
				DataBind();

			//The page hass been told to display the status message
			if (Page.Request.QueryString["PostID"] != null)
			{
				_SuggestionReceived.Visible = true;
			}
		}


		protected override void AttachChildControls()
		{
			Panel pnl = null;
			if (ThisSection.SectionID > 0)
			{
				pnl = FindControl("displayLinks") as Panel;
			}
			else
			{
				pnl = FindControl("displayWelcome") as Panel;
			}

			pnl.Visible = true;

			if (AllowPaging)
			{
				FindControl("PagingArea").Visible = true;
			}

			_Sorting = FindControl("LinkSorting") as LinkSorting;
			_SuggestionReceived = FindControl("SuggestionReceived") as StatusMessage;
			_Links = FindControl("LinkRepeater") as RepeaterPlusNone;
			_Links.ItemDataBound += new RepeaterItemEventHandler(_Links_ItemDataBound);
			_Links.NoneItemsDataBound += new RepeaterItemEventHandler(_Links_NoneItemsDataBound);
			_Pager = FindControl("PagerControl") as LinkPageControl;

			if (_Sorting != null)
			{
				_Sorting.SortChanged += new FourRoads.Links.Controls.LinkSorting.SortOptionsChanged(_Sorting_SortChanged);
			}
		}

		protected ArrayList ErrorState(string message)
		{
			ArrayList arr = new ArrayList();

			ResLinkLink tmpLink = new ResLinkLink();
	
			tmpLink.Subject = "";
			tmpLink.LinkUrl = "";
			tmpLink.Body = ResourceManager.GetString(message);

			arr.Add(tmpLink);

			return arr;
		}

		private void DataBindLinks(LinkViewSort sort)
		{
			if (ViewLinksRight)
			{
				if (AllowPaging == true)
				{
					ResLinkLinksSet rls = ThisSection.GetPagedLinks( CurrentPage , PageSize , sort );

					if (_Pager != null)
					{
						_Pager.CurrentPage = CurrentPage;
						_Pager.TotalPages = (int)System.Math.Ceiling((double)(rls.MoreRecords + (PageSize * CurrentPage)) / (double)PageSize);
						_Pager.SelectedPage = CurrentPage;
						_Pager.QueryName = "Page";
						_Pager.NavigateUrl = ResLinkUrls.Instance().ViewSection(ThisSection.SectionID);
						_Pager.VisibleOnOnePage = _Pager.TotalPages > 1;
					}
					_Links.DataSource = rls.Links;
				}
				else
				{
					_Links.DataSource = ThisSection.GetAllLinks(sort);
				}
			}

			_Links.DataBind();

			if (_Sorting != null && _Links.Items.Count == 0)
			{
				_Sorting.Visible = false;
			}
		}

		public override void DataBind()
		{
			if (Page.IsPostBack == false)
			{
				base.DataBind();

				DataBindLinks(LinkViewSort.Name);

				if (ThisSection.Links.Length == 0 || View != viewType.Auto || !ViewLinksRight)
				{
					HtmlGenericControl ctrl = FindControl("lowerBreadCrumb") as HtmlGenericControl;

					ctrl.Visible = false;
				}

				if (View != viewType.Auto)
				{
					HtmlGenericControl ctrl = FindControl("upperBreadCrumb") as HtmlGenericControl;

					ctrl.Visible = false;
				}
			}
		}

		private ResLinkConfiguration config = ResLinkConfiguration.Instance();

		private void _Links_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || 
				e.Item.ItemType == ListItemType.AlternatingItem )
			{
				ResLinkLink rl = ((ResLinkLink)e.Item.DataItem);

				e.Item.Visible = View == viewType.Auto 
					|| (View == viewType.Moderation && !rl.IsApproved) || (View == viewType.Moderation && rl.CommentModerationCount > 0)
					|| (View == viewType.DeadLinks && rl.ReportedDead);

				if (config.AdvertRepeatFrequency > 0 && e.Item.ItemIndex > 0)
				{
					if (System.Math.IEEERemainder(e.Item.ItemIndex , config.AdvertRepeatFrequency) == 0)
					{	//Whole Number
						AdPart part = e.Item.FindControl("InterLInkAdd") as AdPart;
						part.Visible = true;
					}
				}

				//resolve the resource link and pass it into the ReslinkLinkView and tell it to databind
				ResLinkLinkView lnkView = e.Item.FindControl("LinkView") as ResLinkLinkView;

				lnkView.ModerationView = View == viewType.Moderation;
				lnkView.LinkPost = rl;
				lnkView.DataBind();
			}
		}

		private void _Links_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{
			ResLinkNoLinks noLinks =  e.Item.FindControl("NoLinks") as ResLinkNoLinks;
			noLinks.Visible = true;
		}

		/// <summary>
		/// THis is fired when the sort changes
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void _Sorting_SortChanged(object sender, LinkSortingEventArgs e)
		{
			DataBindLinks(e.SortOrder);
		}
	}
}
